<template>
  <div class="workflow-toolbar">
    <!-- 基础节点区域 -->
    <div class="nodes-section">
      <h4 class="section-title">基于节点</h4>
      <div class="node-tools">
        <div 
          v-for="nodeType in nodeTypes" 
          :key="nodeType.type"
          class="node-tool"
          draggable="true"
          @dragstart="handleDragStart($event, nodeType.type)"
          :title="nodeType.description"
        >
          <div class="node-icon" :style="{ backgroundColor: nodeType.color }">
            <i v-if="nodeType.iconFont" class="iconfont" :class="nodeType.iconFont"></i>
            <span v-else>{{ nodeType.label }}</span>
          </div>
          <span class="node-label">{{ nodeType.label }}</span>
        </div>
      </div>
    </div>

    <!-- 插件区域 -->
    <div class="plugins-section">
      <div class="plugins-header">
        <h4 class="section-title">插件</h4>
        <el-button size="small" type="primary" plain :icon="Plus" @click="openAddPlugin">新增插件</el-button>
      </div>
      <div class="plugin-tools">
        <div
          v-for="tool in toolTypes"
          :key="tool.type"
          class="node-tool"
          draggable="true"
          @dragstart="handlePluginDrag($event, tool)"
          @click="handlePluginClick(tool.type)"
          :title="tool.description"
        >
          <div class="node-icon" :style="{ backgroundColor: tool.color || '#7184a8' }">
            <i v-if="tool.iconFont" class="iconfont" :class="tool.iconFont"></i>
            <span v-else-if="tool.iconUnicode" class="iconfont">{{ tool.iconUnicode }}</span>
            <span v-else>{{ tool.label || tool.type }}</span>
          </div>
          <span class="node-label">{{ tool.label || tool.type }}</span>
        </div>
      </div>
      <el-dialog v-model="addPluginDialogVisible" title="新增插件" width="420px">
        <el-form :model="pluginForm" label-width="80px">
          <el-form-item label="名称">
            <el-input v-model="pluginForm.label" placeholder="请输入插件名称" />
          </el-form-item>
          <el-form-item label="类型">
            <el-input v-model="pluginForm.type" placeholder="不填则根据名称自动生成" />
          </el-form-item>
          <el-form-item label="颜色">
            <el-color-picker v-model="pluginForm.color" />
          </el-form-item>
          <el-form-item label="图标">
            <el-select v-model="pluginForm.iconUnicode" placeholder="选择图标" style="width: 100%">
              <el-option v-for="opt in iconOptions" :key="opt.unicode" :label="opt.label" :value="opt.unicode">
                <span class="iconfont" style="margin-right:8px">{{ opt.unicode }}</span>{{ opt.label }}
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="说明">
            <el-input type="textarea" v-model="pluginForm.description" placeholder="请输入说明" />
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="addPluginDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="savePlugin">保存</el-button>
        </template>
      </el-dialog>
    </div>

    <!-- 快捷键提示：左下角悬浮图标与美化弹窗 -->
    <div class="help-fab">
      <el-tooltip placement="right" popper-class="workflow-help-tooltip">
        <template #content>
          <div class="tooltip-content">
            <el-icon><MoreFilled /></el-icon>
            <span>快捷键与说明</span>
          </div>
        </template>
        <el-button 
          class="help-fab-btn"
          type="primary"
          size="small"
          plain
          circle
          :icon="MoreFilled"
          @click="openShortcuts"
        />
      </el-tooltip>
      <el-dialog 
        v-model="shortcutDialogVisible" 
        title="快捷键与说明" 
        width="520px"
        custom-class="shortcut-dialog"
        :append-to-body="true"
      >
        <div class="dialog-content">
          <h4 class="dialog-title">常用快捷键</h4>
          <ul class="shortcut-list">
            <li><kbd>Ctrl</kbd> + <kbd>A</kbd> 全选</li>
            <li><kbd>Ctrl</kbd> + <kbd>C</kbd> 复制</li>
            <li><kbd>Ctrl</kbd> + <kbd>V</kbd> 粘贴</li>
            <li><kbd>Ctrl</kbd> + <kbd>X</kbd> 剪切</li>
            <li><kbd>Ctrl</kbd> + <kbd>Z</kbd> 撤销</li>
            <li><kbd>Delete</kbd> 删除</li>
            <li><kbd>Shift</kbd> + 拖动 框选</li>
            <li><kbd>Space</kbd> + 拖动 移动画布</li>
          </ul>
          <h4 class="dialog-title">操作说明</h4>
          <ul class="doc-list">
            <li>从左侧拖拽节点到画布以创建</li>
            <li>悬停边可调整箭头与路径</li>
            <li>循环泳道内子节点仅在同泳道内互连</li>
          </ul>
        </div>
      </el-dialog>
    </div>

    <!-- 隐藏的文件输入 -->
    <input 
      ref="fileInput" 
      type="file" 
      accept=".json" 
      style="display: none" 
      @change="handleFileSelect"
    />
  </div>
</template>

<script>
import { defineComponent, ref, computed } from 'vue'
import { 
  Check, Upload, Download, RefreshLeft, RefreshRight, 
  ZoomIn, ZoomOut, FullScreen, Aim, QuestionFilled ,MoreFilled, Plus
} from '@element-plus/icons-vue'
import { componentRegistry } from '@/components/WorkFlow/core/ComponentRegistry'

/**
 * 工作流工具栏组件
 * 提供节点拖拽、操作工具和快捷键说明
 */
export default defineComponent({
  name: 'WorkflowToolbar',
  
  components: {
    Check, Upload, Download, RefreshLeft, RefreshRight,
    ZoomIn, ZoomOut, FullScreen, Aim, QuestionFilled,MoreFilled, Plus
  },

  setup(props, { emit }) {
    const fileInput = ref(null)
    const shortcutDialogVisible = ref(false)
    const addPluginDialogVisible = ref(false)
    const pluginForm = ref({ label: '', type: '', color: '#7184a8', iconUnicode: '', description: '' })
    const iconOptions = ref([
      { label: '开始', unicode: '\ue64d' },
      { label: 'API', unicode: '\ue9eb' },
      { label: '代码', unicode: '\ue64f' },
      { label: 'LLM', unicode: '\ue885' },
      { label: '条件', unicode: '\ue6d8' },
      { label: '循环', unicode: '\ue8cd' },
      { label: '结束', unicode: '\ue600' }
    ])

    // 计算属性：从组件注册表获取所有节点类型
    const nodeTypes = computed(() => componentRegistry.getNodeTypes())
    // 计算属性：从组件注册表获取所有插件类型
    const toolTypes = ref(componentRegistry.getToolTypes ? componentRegistry.getToolTypes() : [])

    /**
     * 处理节点工具拖拽开始
     * @param {DragEvent} event - 拖拽事件
     * @param {string} nodeType - 节点类型
     */
    const handleDragStart = (event, nodeType) => {
      event.dataTransfer.setData('application/x-node-type', nodeType)
      event.dataTransfer.effectAllowed = 'copy'
      emit('node-drag-start', event, nodeType)
    }

    /**
     * 处理插件点击事件
     * @param {string} toolType - 插件类型
     */
    const handlePluginClick = (toolType) => {
      emit('tool-click', toolType)
    }

    /**
     * 插件拖拽到画布
     */
    const handlePluginDrag = (event, tool) => {
      const payload = JSON.stringify({
        type: tool.type,
        label: tool.label,
        color: tool.color,
        iconUnicode: tool.iconUnicode
      })
      event.dataTransfer.setData('application/x-node-type', 'plugin')
      event.dataTransfer.setData('application/x-plugin-config', payload)
      event.dataTransfer.effectAllowed = 'copy'
    }

    /**
     * 打开新增插件弹窗
     */
    const openAddPlugin = () => {
      addPluginDialogVisible.value = true
    }

    /**
     * 根据名称生成类型标识（下划线小写）
     * @param {string} label - 名称
     * @returns {string} 生成的类型
     */
    const genTypeFromLabel = (label) => {
      return (label || '').trim().toLowerCase().replace(/\s+/g, '_').replace(/[^a-z0-9_]/g, '') || `plugin_${Date.now()}`
    }

    /**
     * 保存新增插件并刷新列表
     */
    const savePlugin = () => {
      const form = pluginForm.value
      const type = (form.type && form.type.trim()) ? form.type.trim() : genTypeFromLabel(form.label)
      componentRegistry.registerTool(type, {
        label: form.label || type,
        description: form.description || '自定义插件',
        color: form.color,
        iconUnicode: form.iconUnicode
      })
      // 刷新本地列表
      toolTypes.value = componentRegistry.getToolTypes()
      addPluginDialogVisible.value = false
      pluginForm.value = { label: '', type: '', color: '#7184a8', iconUnicode: '', description: '' }
    }

    /**
     * 打开快捷键与说明弹窗
     */
    const openShortcuts = () => {
      shortcutDialogVisible.value = true
    }

    const handleImport = () => {
      fileInput.value?.click()
    }

    const handleFileSelect = (event) => {
      const file = event.target.files[0]
      if (file) {
        emit('import', file)
      }
      event.target.value = '' // 重置文件输入
    }

    const handleUndo = () => {
      emit('undo')
    }

    const handleRedo = () => {
      emit('redo')
    }

    const handleZoomIn = () => {
      emit('zoom-in')
    }

    const handleZoomOut = () => {
      emit('zoom-out')
    }

    const handleFitView = () => {
      emit('fit-view')
    }

    const handleCenter = () => {
      emit('center')
    }

    return {
      fileInput,
      nodeTypes,
      toolTypes,
      handleDragStart,
      handlePluginClick,
      handlePluginDrag,
      openAddPlugin,
      addPluginDialogVisible,
      pluginForm,
      iconOptions,
      savePlugin,
      shortcutDialogVisible,
      openShortcuts,
      QuestionFilled,
      MoreFilled,
      Plus,
      handleImport,
      handleFileSelect,
      handleUndo,
      handleRedo,
      handleZoomIn,
      handleZoomOut,
      handleFitView,
      handleCenter
    }
  }
})
</script>

<style scoped>
.workflow-toolbar {
  padding: 16px;
  height: 100%;
  overflow-y: auto;
  position: relative;
}

.toolbar-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 16px;
  border-bottom: 1px solid #e8e8e8;
}

.toolbar-header .title {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: #262626;
}

.action-buttons {
  display: flex;
  gap: 8px;
}

.section-title {
  margin: 0 0 12px 0;
  font-size: 14px;
  font-weight: 600;
  color: #595959;
}

.nodes-section,
.tools-section,
.shortcuts-section {
  margin-bottom: 24px;
}

.node-tools {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 12px;
}

.plugin-tools {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 12px;
}

.plugins-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 8px;
}

.node-tool {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 75px;
  padding: 6px;
  border: 1px solid #e8e8e8;
  border-radius: 6px;
  cursor: grab;
  transition: all 0.2s ease;
  background: #fff;
}

.node-tool:hover {
  border-color: #1890ff;
  box-shadow: 0 2px 8px rgba(24, 144, 255, 0.2);
  transform: translateY(-2px);
}

.node-tool:active {
  cursor: grabbing;
}

.node-icon {
  width: 40px;
  height: 40px;
  border-radius: 6px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 10px;
  font-weight: bold;
  margin-bottom: 8px;
}

.node-icon .iconfont {
  font-size: 22px;
  line-height: 1;
  color: #fff;
}

.node-label {
  font-size: 12px;
  color: #595959;
  text-align: center;
}

.action-tools {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 8px;
}

.shortcuts-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.shortcut-item {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 12px;
}

.shortcut-item kbd {
  padding: 2px 6px;
  background: #f5f5f5;
  border: 1px solid #d9d9d9;
  border-radius: 3px;
  font-family: monospace;
  font-size: 11px;
  min-width: 24px;
  text-align: center;
}

.shortcut-item span {
  color: #595959;
}

.help-fab {
  position: absolute;
  left: 12px;
  bottom: 12px;
}

.help-fab-btn {
  box-shadow: 0 8px 24px rgba(40, 113, 206, 0.35);
}

.dialog-title {
  margin: 12px 0 8px;
  font-size: 14px;
  font-weight: 600;
}

.doc-list {
  padding-left: 18px;
}

/* 美化弹窗（scoped 下使用 :deep 选择器） */
:deep(.shortcut-dialog) {
  border-radius: 10px;
}
:deep(.shortcut-dialog .el-dialog__header) {
  background: #2871CE;
  color: #fff;
}
:deep(.shortcut-dialog .el-dialog__headerbtn .el-dialog__close) {
  color: #fff;
}
:deep(.shortcut-dialog .el-dialog__body) {
  padding: 16px 20px;
}

/* Tooltip 样式与内容布局 */
:deep(.workflow-help-tooltip) {
  padding: 8px 10px;
}
.tooltip-content {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 6px;
}
.tooltip-content .el-icon {
  color: #3865a1;
}
</style>
